<template>
  <view class="containers">
      <uni-forms ref="inputForm" :modelValue="inputForm" :rules="rules">
          <uni-forms-item label="头像：" name="avatar">
<!--              <uni-data-select v-model="inputForm.type" :localdata="range" placeholder="请选择"></uni-data-select>-->
              <image :src="inputForm.avatar ? baseUrl + inputForm.avatarUrl : '../../../static/images/mine/mine_personal.svg'" @click="uploadFn"></image>
          </uni-forms-item>
          <uni-forms-item label="用户类型：" name="userType" v-if="inputForm.userType">
              <uni-data-select v-model="inputForm.userType" :localdata="range" disabled placeholder="请选择"></uni-data-select>
          </uni-forms-item>
          <uni-forms-item label="用户名：" name="nickName">
              <uni-easyinput :disabled="Boolean(inputForm.nickName)" v-model="inputForm.nickName" placeholder="请输入"/>
          </uni-forms-item>
          <uni-forms-item label="姓名：" name="userName" required>
              <uni-easyinput v-model="inputForm.userName" placeholder="请输入" />
          </uni-forms-item>
          <uni-forms-item label="性别：" name="sex">
              <uni-data-checkbox v-model="inputForm.sex" :localdata="sexs" placeholder="请选择" />
          </uni-forms-item>
    <!--          <uni-forms-item label="密码" required name="password">
                  <uni-easyinput v-model="inputForm.password" placeholder="请输入密码" />
              </uni-forms-item>-->
          <uni-forms-item label="手机号：" name="phoneNumber">
              <uni-easyinput v-model="inputForm.phoneNumber" placeholder="请输入" maxlength="11"/>
          </uni-forms-item>
          <uni-forms-item label="邮箱：" name="email">
              <uni-easyinput v-model="inputForm.email" placeholder="请输入" />
          </uni-forms-item>
          <uni-forms-item label="出生日期：" name="birthday">
              <uni-datetime-picker v-model="inputForm.birthday" :clear-icon="false" type="date" placeholder="请选择" />
          </uni-forms-item>
          <uni-forms-item label="公司名称/学校名称：" name="company">
              <uni-data-select v-model="inputForm.company" :localdata="companyList" label="请选择公司/学校"></uni-data-select>
          </uni-forms-item>
          <uni-forms-item label="专业：" name="profession">
              <uni-data-select v-model="inputForm.profession" :localdata="majorList" label="请选择专业"></uni-data-select>
          </uni-forms-item>
<!--          <uni-forms-item label="专业：" name="">
              <uni-easyinput v-model="inputForm." placeholder="请输入" />
          </uni-forms-item>-->
      </uni-forms>
      
      <view class="btnBox">
          <button type="primary" @click="submit" class="btn">保存</button>
      </view>
  </view>
</template>

<script>
import config from '@/config'
  export default {
      data() {
      return {
          inputForm: {
              id: '',
              avatar: '',
              avatarUrl: '',
              birthday: '',
              company: '',
              companyName: '',
              email: '',
              groupName: '',
              nickName: '',
              userName: '',
              phoneNumber: '',
              sex: 1,
              userType: 1,
              profession: '',
              baseUrl: ''
          },
          majorList: [],
          companyList:[],
          // 校验规则
          rules: {
              nickName: {
                  rules: [{
                      required: true,
                      errorMessage: '用户名不能为空'
                  }, {
                      minLength: 2,
                      maxLength: 20,
                      errorMessage: '用户名长度在 2-20位之间'
                  }]
              },
              userName: {
                  rules: [{
                      required: true,
                      errorMessage: '姓名不能为空'
                  }, {
                      minLength: 2,
                      maxLength: 10,
                      errorMessage: '姓名长度在 2-10位之间'
                  }]
              },
              phoneNumber: {
                  rules: [{
                      pattern: /^1[0-9][0-9]\d{8}$/,
                      errorMessage: '请输入正确的手机号码'
                  }]
              },
              email: {
                  rules: [{
                      pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
                      errorMessage: '请输入正确的邮箱'
                  }]
              }
          },
    
          range: [
                  {
                      value: 1,
                      text: '所外学生用户'
                  },
                  {
                      value: 2,
                      text: '所外企业用户'
                  },
          ],
    
          sexs: [{
              value: 1,
              text: '男'
          },
              {
                  value: 2,
                  text: '女'
              }
          ],
          token: ''
      }
    },
    onLoad() {
        this.token = uni.getStorageSync('token')
        this.baseUrl = uni.$config.baseUrl
        this.getUser()
        this.majorType()
        this.companyFn()
    },
    methods: {
      getUser() {
          this.$modal.loading('加载中···')
          this.$request({
              url: '/user/currentUser',
              method: 'get',
              params: {}
          }).then(({ data }) => {
              setTimeout(()=> {
                  this.$modal.closeLoading()
              }, 1000)
              this.inputForm = this.recover(this.inputForm, data)
          }).catch(() => {
              setTimeout(()=> {
                  this.$modal.closeLoading()
              }, 1000)
          })
      },
        // 专业类型
        majorType() {
            this.majorTypeList = [];
            this.$request({
                url: "/dict/register/major",
                method: "get",
            }).then(({ data }) => {
                data.map((item) => {
                    this.majorList.push({
                        value: item.id,
                        text: item.name,
                    });
                });
            });
        },
    
        // 公司信息列表
        companyFn(){
            this.companyList = [];
            this.$request({
                url: "/dict/register/company",
                method: "get",
            }).then(({ data }) => {
                data.map((item) => {
                    this.companyList.push({
                        value: item.id,
                        text: item.name,
                    });
                });
            });
        },
        submit() {
            
            this.$refs.inputForm.validate().then(res => {
                this.$request({
                    url: '/user/edit',
                    method: 'post',
                    data: {
                        ...this.inputForm
                    },
                }).then(({ data }) => {
                    setTimeout(()=> {
                        this.$modal.closeLoading()
                    }, 1000)
                    this.$toast('保存成功')
                    setTimeout( ()=> {
                        uni.navigateBack({
                        delta: 1
                    });
                    },1000)
                      
                })
            })
        },
    
        uploadFn(){
            let that = this
            let type = ['.png','.jpg','.jpeg','.svg']
            uni.chooseFile({
                extension: type,
                count: 1,
                type: 'image',
                success: function (res) {
                    let size = Number(res.tempFiles[0].size / 1024 / 1024)
                    if (size > 10) {
                        that.$toast('仅支持上传10MB以内的图片')
                        return true
                    }
                    let num = 0
                    let fileType = []
                    let hasType = []
                    res.tempFiles.forEach(item => {
                        fileType = item.name.split('.')
                        hasType = type.filter(item => item === '.' + fileType[fileType.length - 1])
                        if (hasType && hasType.length === 0) {
                            num++
                        }
                    })
                    if (num > 0) {
                        that.$toast('仅支持' + type.join(',') + '格式文件')
                        return true
                    }
                    res.tempFilePaths.forEach(item => {
                        uni.uploadFile({
                            url: config.baseUrl + '/file/upload',
                            header: {
                                token: that.token,
                            },
                            filePath: item,
                            name: 'file',
                            formData: {
                            },
                            success: (data) => {
                                let tempData = JSON.parse(data.data)
                                that.inputForm.avatar = tempData.data.id
                                that.inputForm.avatarUrl = tempData.data.downloadUrl
                            },
                            fail: uploadFileError => {
                                // 处理上传失败的错误
                            }
                        })
                    })
                }
            })
        },
    
        /**
         * 表单对象赋值:
         * 对目标对象存在且源对象同样存在的属性，全部覆盖；
         * 目标对象不存在但是源对象存在的属性， 全部丢弃；
         * 目标对象存在但是源对象不存在的属性，如果是字符串赋值为空串，其余类型赋值为undefined
         *
         * @param target {Object} 被覆盖属性的对象
         * @param source {Object} 提供值的对象
         */
        recover (target, source) {
            if (target === undefined || target === null) {
                throw new TypeError('Cannot convert first argument to object')
            }
            let to = Object(target)
            if (source === undefined || source === null) {
                return to
            }
            let keysArray = Object.keys(Object(target))
            for (let nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
                let nextKey = keysArray[nextIndex]
                let desc = Object.getOwnPropertyDescriptor(target, nextKey)
                if (desc !== undefined && desc.enumerable) {
                    if (to.hasOwnProperty(nextKey)) {
                        if (to[nextKey] instanceof Array) {
                            to[nextKey] = source[nextKey]
                        } else if (to[nextKey] instanceof Object) {
                            recover(to[nextKey], source[nextKey])
                        } else if (source[nextKey] !== undefined) {
                            to[nextKey] = source[nextKey]
                        } else if (typeof (to[nextKey]) === 'string') {
                            to[nextKey] = ''
                        } else {
                            to[nextKey] = undefined
                        }
                    }
                }
            }
            return to
        }
    }
  }
</script>

<style lang="scss" scoped>
.containers {
    padding: 40rpx 30rpx;
    display: grid;
    grid-template-columns: 1fr;
    //grid-template-rows: 360rpx 1fr;
    //height: calc(100vh - 176rpx);
    ::v-deep{
        .is-input-border{
            border: none;
        }
        .uni-select{
            border: none;
            height: 100rpx;
            font-family: 思源黑体;
            font-size: 30rpx;
        }
        .uni-select--disabled {
            background-color: #ffffff;
        }
        .uni-select__selector-item{
            font-family: 思源黑体;
            font-size: 30rpx;
            line-height: 40px !important;
            margin: 0;
        }
        .uni-select__input-text {
            text-align: right;
        }
    
        .uni-select__input-placeholder {
            font-size: 28rpx;
            font-family: 思源黑体;
        }
        .uni-data-checklist .checklist-group{
            justify-content: flex-end;
            .checklist-box{
                margin: 38rpx 20rpx;
            }
        }
        .uni-date-x--border{
            border: none;
        }
        .uni-date-x {
            flex-direction: row-reverse;
            padding-right: 20rpx;
        }
        .uni-date__x-input {
            height: 100rpx;
            font-size: 30rpx;
            overflow: hidden;
            line-height: 100rpx;
            text-align: right;
            font-family: 思源黑体;
        }
        .uni-forms-item{
            min-height: 100rpx;
            border-radius: 16rpx;
            margin-bottom: 64rpx;
            background: #FFFFFF;
        }
        .uni-forms-item__content{
            text-align: right;
        }
        .uni-easyinput__content-input{
            height: 100rpx;
            font-family: 思源黑体;
            font-size: 30rpx;
            font-weight: normal;
        }
        .uni-forms-item__label{
            min-height: 100rpx;
            height: auto;
            padding-left: 28rpx;
            font-family: 思源黑体;
            font-size: 30rpx;
            font-weight: normal;
            color: #1C2126;
            white-space: nowrap;
            min-width: 200rpx;
            width: auto !important;
            /*position: relative;
            &:before{
                content: '*';
                position: absolute;
                font-size: 24rpx;
                color: #F53F3F;
                top: calc(50% - 12rpx)  ;
                left: 16rpx;
            }*/
        }
        .uni-easyinput__placeholder-class {
            font-size: 28rpx;
            font-family: 思源黑体;
        }
        .uni-forms-item__error {
            right: 20rpx;
            left: auto;
            font-size: 28rpx;
            font-family: 思源黑体;
            padding-top: 18rpx;
        }
        .uni-easyinput {
            text-align: right;
            padding-right: 20rpx;
        }
    }
    image{
        width: 120rpx;
        height: 120rpx;
        margin: 20rpx;
    }
    .btnBox{
        display: grid;
        justify-content: center;
        align-items: center;
        grid-template-columns: 1fr;
        .btn{
            width: 100%;
            background: #0084FF;
            font-family: Poppins;
            font-size: 32rpx;
            font-weight: 600;
            color: #FFFFFF;
        }
    }
}
::v-deep .is-disabled{
    background-color: white !important;
}
</style>
